﻿using System;
using System.ComponentModel;

namespace Storm.TextEditor.Interacting
{
	/// <summary>
	/// Represents a timer that acts like a WeakReference.
	/// </summary>
	[ToolboxItem(false)]
	public class WeakTimer
		: Component
	{
		#region Fields

		private int  tickCount = 0;
		private int  interval  = 100;
		private bool enabled   = true;

		private Container components = null;

		#region Events

		/// <summary>
		/// Occurs when the WeakTimer ticks.
		/// </summary>
		public event EventHandler Tick = null;

		#endregion

		#endregion

		#region Properties

		/// <summary>
		/// Gets or sets the interval of the WeakTimer.
		/// </summary>
		public int Interval
		{
			get { return interval; }
			set { interval = value; }
		}

		/// <summary>
		/// Gets or sets whether the WeakTimer is enabled.
		/// </summary>
		public bool Enabled
		{
			get { return enabled; }
			set { enabled = value; }
		}

		#endregion

		#region Methods

		#region Public

		/// <summary>
		/// Raises the Tick event of the WeakTimer.
		/// </summary>
		/// <param name="s">Sender object.</param>
		/// <param name="e">EventArgs.</param>
		public void DoTick(object s, EventArgs e)
		{
			tickCount++;
			if (this.Enabled == true)
			{
				if (tickCount >= (this.Interval / WeakTimerHelper.Speed))
				{
					tickCount = 0;

					try
					{
						if (this.Tick != null)
							this.Tick(s, e);
					}
					catch
					{
					}
				}
			}
		}

		#endregion

		#endregion

		/// <summary>
		/// Initializes a new instance of WeakTimer.
		/// </summary>
		public WeakTimer()
		{
			// Required by the Windows Forms Designer.
			InitializeComponent();

			WeakTimerHelper.Attach(this);
		}

		/// <summary>
		/// Initializes a new instance of WeakTimer.
		/// </summary>
		public WeakTimer(IContainer container)
		{
			// Required by the Windows Forms Designer.
			InitializeComponent();

			container.Add(this);
			WeakTimerHelper.Attach(this);
		}

		~WeakTimer()
		{
			WeakTimerHelper.Detach(this);
		}

		#region Component Designer generated code

		private void InitializeComponent()
		{
			components = new System.ComponentModel.Container();
		}

		#endregion
	}
}
